//
//  ThmImageView.m
//  Nicejinux.NET
//
//  Created by Nicejinux on 12. 3. 8..
//  Copyright (c) 2012 Nicejinux.NET. All rights reserved.
//

#import "ThmImageView.h"
#import "ASIHTTPRequest.h"
#import "ASIDownloadCache.h"
#import "AnimationUtil.h"

@interface ThmImageView ()

@property (nonatomic, strong)   NSString                    *localFilePath;
@property (nonatomic, strong)   UIActivityIndicatorView     *loadingView;
@property (nonatomic, strong)   ASIHTTPRequest              *asiRequest;
@property (nonatomic, strong)   NSString                    *noImageFileName;


- (id)configWithDefaultImage:(NSString*)defaultImageName
              remoteImageURL:(NSString*)remoteImageURLArg 
            defaultFrameRect:(CGRect)defaultFrameRect;

- (void)reloadImageFromLocal:(NSString*)newFilePath;

@end

@implementation ThmImageView

@synthesize localFilePath;
@synthesize loadingView;
@synthesize asiRequest;
@synthesize noImageFileName;
@synthesize delegate;

+ (id)imageViewWithDefaultImage:(NSString*)defaultImageName
              remoteImageURL:(NSString*)remoteImageURLArg
            defaultFrameRect:(CGRect)defaultFrameRect
{
    id obj = [[self alloc] init];
    [obj configWithDefaultImage:defaultImageName
                 remoteImageURL:remoteImageURLArg 
               defaultFrameRect:defaultFrameRect];
    
    return obj;
}

- (id)configWithDefaultImage:(NSString*)defaultImageName
              remoteImageURL:(NSString*)remoteImageURLArg 
            defaultFrameRect:(CGRect)defaultFrameRect
{
    self.frame = defaultFrameRect;
    
    
    if ([defaultImageName length])
    {
        self.image = [UIImage imageNamed:defaultImageName];
    }
    
    [self loadURLImage:remoteImageURLArg];
    
    return self;
}

- (void)setClearImage
{
    self.alpha = 1.0;
}

- (void)setRowAlphaImage
{
    self.alpha = 0.6;
}

- (void)loadURLImage:(NSString*)remoteImageURLArg
{
    if ([remoteImageURLArg length])
    {
        [asiRequest clearDelegatesAndCancel];
        self.image = nil;

        NSURL *url = [NSURL URLWithString:remoteImageURLArg];
        
        self.asiRequest = [ASIHTTPRequest requestWithURL:url];
        
        [asiRequest setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
        [asiRequest setDelegate:self];
        
        self.localFilePath = [[ASIDownloadCache sharedCache] pathToStoreCachedResponseDataForRequest:asiRequest];
        
        // cached용으로 저장된 file이 있으면 그것을 load.
        NSFileManager *fm = [NSFileManager defaultManager];
        if ([fm fileExistsAtPath:localFilePath])
        {
            self.image = [UIImage imageWithContentsOfFile:localFilePath];
        }
        else
        {
            // 없으면 activity indicator
            if (![loadingView isAnimating])
            {
                [self setRowAlphaImage];
                self.loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
                loadingView.center = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2);
                [self addSubview:loadingView];
                [loadingView startAnimating];
            }
        }
        
        [asiRequest startAsynchronous];
    }
}


/**
 서버로부터 이미지를 수신중에는 loadingImageName으로 전달된 이미지를 보여주고 있고,
 서버로부터 이미지를 수신 완료 한 후에는 수신된 이미지를 보여준다.
 
 기존에 cache되어 있던 이미지가 있는 경우, cache 이미지를 우선 보여준다.
 
 cache된 이미지가 없었고 이미지를 수신할 수 없는 경우 noImageName으로 전달된 이미지를 보여준다.
 
 이미지를 수신중에 activity indicator를 보여주지 않는다.
 
 @param remoteImageURLArg 수신받을 이미지 URL
 @param loadingImageName 이미지 수신중 표시할 이미지 파일명
 @param noImageName 수신받을 이미지가 없는 경우 표시할 이미지 파일명
 @returns 
 @exception 
 */
- (void)loadURLImage:(NSString*)remoteImageURLArg 
        loadingImage:(NSString*)loadingImageName 
             noImage:(NSString*)noImageName
{
    NSLog(@"REMOTE FILENAME %@ ", remoteImageURLArg);

    if ([remoteImageURLArg length])
    {
        noImageFileName = noImageName;
        
        [asiRequest clearDelegatesAndCancel];
        self.image = nil;
        
        NSURL *url = [NSURL URLWithString:remoteImageURLArg];
        
        self.asiRequest = [ASIHTTPRequest requestWithURL:url];
        [asiRequest setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
        [asiRequest setDelegate:self];
        
        self.localFilePath = [[ASIDownloadCache sharedCache] pathToStoreCachedResponseDataForRequest:asiRequest];
        
        // cached용으로 저장된 file이 있으면 그것을 load.
        NSFileManager *fm = [NSFileManager defaultManager];
        if ([fm fileExistsAtPath:localFilePath])
        {
            self.image = [UIImage imageWithContentsOfFile:localFilePath];
        }
        else
        {
            // 없으면 loading image 표시
            self.image = [UIImage imageNamed:loadingImageName];
        }
        
        [asiRequest startAsynchronous];  
    }
    
}


- (void)reloadImageFromLocal:(NSString*)newFilePath
{
//    NSLog(@"%s - %@", __func__, newFilePath);
    
    [loadingView removeFromSuperview];
    self.loadingView = nil;
    
    if ([newFilePath length])
    {
        [AnimationUtil quartzAnimation:self :0.5f];
        self.image = [UIImage imageWithContentsOfFile:newFilePath];
        [self setClearImage];
    }
}


- (void)requestFinished:(ASIHTTPRequest *)request
{
//    NSLog(@"%s response status code : %d", __func__, [request responseStatusCode]);
    
    [delegate detailThumbLoadingFinished];
    
    [loadingView removeFromSuperview];
    self.loadingView    = nil;
    
    int responseStatusCode = [request responseStatusCode];
    if (responseStatusCode == 200) {
        [self reloadImageFromLocal:localFilePath];
        NSLog(@"SUCCESS %@ !!!!!!!!!!!!!!!", localFilePath);
    }
    else if (responseStatusCode >= 400)
    {
        NSFileManager *fm = [NSFileManager defaultManager];
        if (![fm fileExistsAtPath:localFilePath])
        {
            if ([noImageFileName length])
                self.image = [UIImage imageNamed:noImageFileName];
            NSLog(@"RESP 400 Fail %@ !!!!!!!!!!!!!!!", noImageFileName);
        }
    }
    
    self.asiRequest = nil;
}


- (void)requestFailed:(ASIHTTPRequest *)request
{
//    NSLog(@"%s", __func__);
    
    [loadingView removeFromSuperview];
    self.loadingView    = nil;
    self.asiRequest = nil;
    
    if ([noImageFileName length])
    {
        NSFileManager *fm = [NSFileManager defaultManager];
        if (![fm fileExistsAtPath:localFilePath])
        {
            self.image = [UIImage imageNamed:noImageFileName];
            NSLog(@"REQUEST Fail %@ !!!!!!!!!!!!!!!", noImageFileName);
        }
    }
}


- (void)dealloc
{
    [asiRequest clearDelegatesAndCancel];
}

@end
